#include<iostream>
#include<vector>
using namespace std;


class Solution {
public:
    int countSquares(vector<vector<int>>& matrix) {
        int n = matrix.size();
        int m = matrix[0].size();
        vector<vector<int>> tmpArr(n + 1, vector<int>(m + 1, 0));
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < m + 1; j++) {
                tmpArr[i][j] = tmpArr[i][j - 1] + matrix[i - 1][j - 1];
            }
        }
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < m + 1; j++) {
                tmpArr[i][j] += tmpArr[i - 1][j];
            }
        }
        int maxlen = min(n, m);
        int ans = 0;
        for (int L = 1; L <= maxlen; L++) {
            for (int i = L; i <= n; i++) {
                for (int j = L; j <= m; j++) {
                    if (L * L == tmpArr[i][j] + tmpArr[i - L][j - L] - tmpArr[i - L][j] - tmpArr[i][j - L]) {
                        ans++;
                    }
                }
            }
        }
        return ans;
    }
};